import { create } from "zustand";
import { persist } from "zustand/middleware";

interface User {
  id: string;
  username: string;
  name: string;
  email: string;
  avatar: string; // 添加头像字段
}

interface AuthData {
  token: string;
  user: User;
}

// 首先在 stores/index.ts 中添加 loading 状态
interface AppState {
  loading: boolean;
  token: string | null;
  user: User | null;
  setLoading: (loading: boolean) => void;
  setAuth: (data: AuthData) => void;
  getToken: () => string | null;
  logout: () => void;
}

export const useAppStore = create(
  persist<AppState>(
    (set, get) => ({
      token: localStorage.getItem("token"),
      user: null,
      loading: false,
      setLoading: (loading) => set({ loading }),
      setAuth: (data) => {
        set({
          token: data.token,
          user: data.user,
        });
      },
      getToken: () => get().token,
      logout: () => {
        set({ token: null, user: null });
      },
    }),
    {
      name: "app-storage",
    }
  )
);
